<template>
  <s-layout class="set-wrap" title="新增商品" :bgStyle="{ color: '#f7f7f7' }">
    <s-empty v-if="state.list.length === 0 && !state.loading" text="暂无常见问题" icon="/static/collect-empty.png" />

    <view class="flex flex-col px-4 pb-4 bg-white">
      <view class="flex overflow-hidden flex-col bg-white rounded-lg">
        <!-- 商品标题 -->
        <view class="flex items-center py-2">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 商品标题 </view>
          <uni-easyinput
            v-model="state.title"
            placeholder="商品标题"
            type="text"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
          </uni-easyinput>
        </view>
        <u-line></u-line>

        <view class="flex relative items-center py-2">
          <view class="size-full absolute inset-0 z-50" @click="state.showCategory = true"></view>
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 商品分类 </view>
          <uni-easyinput
            v-model="state.category_name"
            placeholder="商品分类"
            type="text"
            :inputBorder="false"
            disabled
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
            <template #right>
              <u-icon name="arrow-right"></u-icon>
            </template>
          </uni-easyinput>
        </view>
        <u-line></u-line>

        <!-- 副标题 -->
        <view class="flex items-center py-2">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 商品副标题 </view>
          <uni-easyinput
            v-model="state.subtitle"
            placeholder="商品副标题"
            type="text"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
          </uni-easyinput>
        </view>
        <u-line></u-line>
        <!-- 供应商价格 -->
        <!-- <view class="flex items-center py-2">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 供应商价格 </view>
          <uni-easyinput
            v-model="state.cost_price"
            placeholder="请输入供应商价格"
            type="digit"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
          </uni-easyinput>
        </view>
        <u-line></u-line> -->
        <!-- 划线价格 -->
        <view class="flex items-center py-2">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 划线价格 </view>
          <uni-easyinput
            v-model="state.original_price"
            placeholder="请输入划线价格"
            type="digit"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
          </uni-easyinput>
        </view>
        <u-line></u-line>
        <!-- 售卖价格 -->
        <view class="flex items-center py-2">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 售卖价格 </view>
          <uni-easyinput
            v-model="state.price"
            placeholder="请输入售卖价格"
            type="digit"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
          </uni-easyinput>
        </view>
        <u-line></u-line>
        <!-- 库存数量 -->
        <view class="flex items-center py-2">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 库存数量 </view>
          <uni-easyinput
            v-model="state.stock"
            placeholder="请输入库存数量"
            type="digit"
            :inputBorder="false"
            placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
            :styles="{ disableColor: '#fff', color: '#333' }"
          >
          </uni-easyinput>
        </view>
        <u-line></u-line>

        <view class="flex flex-col gap-4 py-4 pb-0">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 商品主图 </view>
          <s-uploader v-model:url="state.image" fileMediatype="image" limit="1" mode="grid" :imageStyles="{ width: '168rpx', height: '168rpx' }">
          </s-uploader>
        </view>
        <view class="flex flex-col gap-4 py-4 pb-0">
          <view class="text-[15px] text-[#333333] flex-none w-[5rem]"> 轮播图 </view>
          <s-uploader v-model:url="state.images" fileMediatype="image" limit="3" mode="grid" :imageStyles="{ width: '168rpx', height: '168rpx' }">
          </s-uploader>
        </view>
        <view class="flex flex-col gap-4 py-4 pb-0">
          <view class="text-[15px] text-[#333333] flex-none"> 商品详情 </view>
          <sp-editor
            :toolbar-config="{
              excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
              iconSize: '18px',
            }"
            :defaultContent="state.content"
            @init="initEditor"
            @input="inputOver"
            @upinImage="upinImage"
            @upinVideo="upinVideo"
            @overMax="overMax"
            @addLink="addLink"
            @exportHtml="exportHtml"
          ></sp-editor>
          <!-- //sheep.$api.app.upload(tempUrl, 'ugc'); -->
          <!-- <mp-html :content="state.content" /> -->
        </view>
      </view>
    </view>

    <view class="h-20"></view>

    <view class="fixed right-0 bottom-0 left-0 p-4 bg-white">
      <view class="overflow-hidden py-3 w-full rounded-lg bg-[#0788C8] grid place-items-center" @click="submit">
        <view class="font-medium text-[16px] text-[#FFFFFF]">{{ state.id ? '编辑商品' : '新增商品' }}</view>
      </view>
    </view>
    <!--  -->
    <!--  -->
    <!--  -->
    <u-picker :show="state.showCategory" :columns="[state.list]" keyName="name" @confirm="confirm" @cancel="cancel"></u-picker>
  </s-layout>
</template>

<script setup>
  //sp-editor 导入组件
  import spEditor from '@/uni_modules/sp-editor/components/sp-editor/sp-editor.vue';
  // import { chooseAndUploadFile } from '@/sheep/components/s-uploader/choose-and-upload-file.js';
  import sheep from '@/sheep';

  const state = ref({
    list: [],
    loading: true,
    list: [],
    loading: true,
    showCategory: false,
    title: '', // 商品标题
    subtitle: '', // 商品副标题
    category_ids: '', // 分类ID
    original_price: '', // 划线价
    // cost_price: '', // 供应商价格

    price: '', // 售卖价
    stock: '', // 库存
    image: '', // 主图
    images: [], // 轮播图
    // ----------------
    category_name: '',
    id: '',
  });
  // defaultData();

  onLoad((e) => {
    goodscategory();
    state.value.id = e.id;
  });
  // watch(
  //   () => state.value.id,
  //   (newValue, oldValue) => {
  //     console.log('newValue==> ', newValue);
  //     goodsShow();
  //   },
  // );

  function goodsShow() {
    sheep.$api.yy
      .goodsShow({
        id: state.value.id,
      })
      .then((res) => {
        state.value.title = res.data.title;
        state.value.subtitle = res.data.subtitle;
        state.value.category_ids = res.data.category_ids;
        state.value.original_price = res.data.original_price - 0;
        // state.value.cost_price = res.data.cost_price - 0;
        state.value.price = res.data.price - 0;
        state.value.stock = res.data.stock - 0;
        state.value.image = res.data.image;
        state.value.images = res.data.images;
        state.value.content = res.data.content;
        console.log(' state.value.images ==> ', state.value.images);
        // 根据分类ID查找对应的分类名称
        const categoryItem = state.value.list.find((item) => item.id - 0 === res.data.category_ids - 0);
        if (categoryItem) {
          state.value.category_name = categoryItem.name;
        }
      });
  }

  function goodscategory() {
    sheep.$api.yy.goodscategory().then((res) => {
      if (res.code === 1) {
        state.value.list = res.data;

        if (state.value.id) {
          goodsShow();
        }
      }
    });
  }

  // function defaultData() {
  //   // 填充默认数据
  //   // 随机生成商品标题
  //   const titles = ['精品商品', '热销商品', '限时特惠', '新品上架', '爆款推荐'];
  //   state.value.title = titles[Math.floor(Math.random() * titles.length)];

  //   // 随机生成副标题
  //   const subtitles = ['品质保证', '限时促销', '优惠特卖', '折扣特惠', '超值优惠'];
  //   state.value.subtitle = subtitles[Math.floor(Math.random() * subtitles.length)];

  //   // 随机生成分类ID (1-5)
  //   // state.value.category_ids = String(Math.floor(Math.random() * 5) + 1);

  //   // 随机生成价格 (100-1000)
  //   const basePrice = Math.floor(Math.random() * 900) + 100;
  //   state.value.original_price = String(basePrice);
  //   state.value.cost_price = String(Math.floor(basePrice * 0.6));
  //   state.value.price = String(Math.floor(basePrice * 0.8));

  //   // 随机生成库存 (50-500)
  //   state.value.stock = String(Math.floor(Math.random() * 450) + 50);
  // }

  function submit() {
    let obj = {
      title: state.value.title,
      subtitle: state.value.subtitle,
      category_ids: state.value.category_ids,
      image: state.value.image,
      images: state.value.images.join(','),
      original_price: state.value.original_price,
      // cost_price: state.value.cost_price,
      price: state.value.price,
      stock: state.value.stock,
      content: state.value.content,
    };

    // 根据是否有id判断是编辑还是新增
    const apiMethod = state.value.id ? sheep.$api.yy.goodsEdit : sheep.$api.yy.goodsAdd;

    // 如果是编辑,需要传入id
    if (state.value.id) {
      obj.id = state.value.id;
    }

    apiMethod(obj).then((res) => {
      if (res.code === 1) {
        uni.showToast({
          title: state.value.id ? '编辑成功' : '添加成功',
          icon: 'none',
        });
        // 编辑成功后返回上一页

        // 新增成功后清空表单
        state.value.title = '';
        state.value.subtitle = '';
        state.value.category_ids = '';
        state.value.image = '';
        state.value.images = '';
        state.value.original_price = '';
        // state.value.cost_price = '';
        state.value.price = '';
        state.value.stock = '';
        state.value.content = '';
        state.value.category_name = '';
        setTimeout(() => {
          // 返回上一页并刷新页面
          // 方法一：通过事件总线通知上一页刷新
          // 方法二：设置页面需要刷新的标记
          // const pages = getCurrentPages();
          // if (pages.length > 1) {
          //   // 获取上一页实例
          //   const prevPage = pages[pages.length - 2];
          //   // 设置上一页的刷新标记
          //   if (prevPage.$vm) {
          //     prevPage.$vm.needRefresh = true;
          //   }
          // }
          // uni.$emit('goodsUpdated');

          uni.navigateBack({
            delta: 1,
          });
        }, 200);
      }
    });
  }

  function confirm(e) {
    console.log('e==> ', e.value[0].name);
    state.value.category_ids = e.value[0].id;
    state.value.showCategory = false;
    state.value.category_name = e.value[0].name;
  }
  function cancel() {
    state.value.showCategory = false;
  }
  function initEditor(editorCtx) {
    // 保存编辑器实例，以便在其他地方使用
    state.editorCtx = editorCtx;

    // 示例：如何在编辑器初始化后手动设置内容
    // 注意：如果已经使用 defaultContent 属性，通常不需要这段代码
    // 这里仅作为演示如何手动设置内容的示例
    /*
    if (state.content) {
      editorCtx.setContents({
        html: state.content,
        success: () => {
          console.log('手动设置内容成功')
        },
        fail: (err) => {
          console.error('手动设置内容失败', err)
        }
      })
    }
    */
  }
  function inputOver(e) {
    // 可以在此处获取到编辑器已编辑的内容
    state.value.content = e.html;
  }
  function upinImage(tempFiles, editorCtx) {
    console.log('🚀 ~ upinImage ~ tempFiles:', tempFiles);
    // 参考 s-uploader 组件的上传逻辑
    // if (!tempFiles || !tempFiles.length || !editorCtx) return;

    // // 确保 chooseAndUploadFile 函数可用
    // if (!uniCloud.chooseAndUploadFile) {
    //   uniCloud.chooseAndUploadFile = chooseAndUploadFile;
    // }

    // 直接使用 tempFiles 上传图片
    // 这里假设 tempFiles 已经是从选择器获取的文件对象
    sheep.$api.app
      .upload(tempFiles[0].path, 'ugc')
      .then((result) => {
        console.log('result==> ', result);
        // return;
        editorCtx.insertImage({
          src: result.fullurl,
          width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
          success: function () {
            console.log('插入图片成功');
            uni.showToast({
              title: '插入图片成功',
              icon: 'success',
            });
          },
          fail: function (err) {
            console.error('插入图片失败:', err);
            uni.showToast({
              title: '插入图片失败',
              icon: 'none',
            });
          },
        });
      })
      .catch((err) => {
        console.error('上传图片失败:', err);
        uni.showToast({
          title: '上传图片失败',
          icon: 'none',
        });
      });
  }

  function overMax() {}
  function addLink() {}
  function exportHtml() {}
  function upinVideo(tempFiles, editorCtx) {
    console.log('tempFiles==> ', tempFiles);
    sheep.$api.app
      .upload(tempFiles[0].path, 'ugc')
      .then((result) => {
        console.log('result==> ', result);
        // return;
        editorCtx.insertVideo({
          src: result.fullurl,
          width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
          success: function () {
            console.log('插入图片成功');
            uni.showToast({
              title: '插入图片成功',
              icon: 'success',
            });
          },
          fail: function (err) {
            console.error('插入图片失败:', err);
            uni.showToast({
              title: '插入图片失败',
              icon: 'none',
            });
          },
        });
      })
      .catch((err) => {
        console.error('上传图片失败:', err);
        uni.showToast({
          title: '上传图片失败',
          icon: 'none',
        });
      });
  }
</script>

<style lang="scss" scoped>
  :deep() {
    .uni-forms-item__label .label-text {
      font-size: 28rpx !important;
      color: #333333 !important;
      line-height: normal !important;
    }

    .uni-easyinput__content-input {
      font-size: 28rpx !important;
      color: #333333 !important;
      line-height: normal !important;
      padding-left: 0 !important;
    }

    .uni-easyinput__content-textarea {
      font-size: 28rpx !important;
      color: #333333 !important;
      line-height: normal !important;
      margin-top: 8rpx !important;
    }

    .uni-icons {
      font-size: 40rpx !important;
    }

    .is-textarea-icon {
      margin-top: 22rpx;
    }

    .is-disabled {
      color: #333333;
    }
  }
</style>
